package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if(userId != null){
            Query query = Query.query(Criteria.where("refId").is(userId));
            ApBehaviorEntry one = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //如果查询不到 为空的话 就创建 然后返回对象
            if(one == null){
                //如果用户id不为空的话 使用userid查询 行为实体就是根据当前用户id创建
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                ApBehaviorEntry save = mongoTemplate.save(apBehaviorEntry);
                return save;
            }
           return one;
        }else if(equipmentId != null){
            //如果设备id 不为空的话 行为实体根据设备id创建
            Query query = Query.query(Criteria.where("refId").is(equipmentId));
            ApBehaviorEntry one = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if(one == null) {
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                ApBehaviorEntry save = mongoTemplate.save(apBehaviorEntry);
                return save;
            }
            return one;
        }else {
            //如果都为空 返回空
            return null;
        }
    }
}
